#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<cerrno>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
using namespace std;
const uint16_t port = 8083;//端口号
int main()
{
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
      perror("socket:");
      exit(1);
    }
    struct sockaddr_in local;
    memset(&local,0,sizeof(local));
    local.sin_family = AF_INET;//协议家族
    local.sin_addr.s_addr = INADDR_ANY;//IP
    local.sin_port = htons(port);//端口号 主机序-》网络字节序！！！
    if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
    {
      perror("bind:");
      exit(2);
    }

    //提供服务
    bool quit = false;
#define NUM 1024
    char buf[NUM] = {0};
    while(!quit)
    {
        memset(buf,0,sizeof(buf));//清空内容
        struct sockaddr_in peer;//接收客户端的网络信息
        socklen_t len = sizeof(peer);
        ssize_t ret = recvfrom(sock,buf,sizeof(buf)-1,0,(struct sockaddr*)&peer,&len);
        if(ret > 0)
        {
          buf[ret] = '\0';
          cout << "client:#" <<" "<<buf<<endl;

          //服务端响应
          string msg = "hello I am server";
          sendto(sock,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,len);
        }
    }
    return 0;
}
